package bean;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import tpInterface.ICart;

/**
 *
 * @author SonTT
 */
@ManagedBean
@RequestScoped
public class CartBean implements ICart {

    private static final Logger LOG = Logger.getLogger(CartBean.class.getName());
    private Map<String, Integer> cart;

    /**
     * Creates a new instance of CartBean
     */
    public CartBean() {
    }

    @Override
    public Map<String, Integer> getCart() {
        if (cart == null) {
            cart = new HashMap<String, Integer>(10);
        }

        cart.put("p1", 1);
        cart.put("p2", 2);
        cart.put("p3", 3);
        cart.put("p4", 4);

        return cart;
    }

    @Override
    public String addCart(String productID) {
        if (cart == null) {
            cart = new HashMap<String, Integer>(10);
        } else {
            if (cart.containsKey(productID)) {
                Integer q = cart.get(productID);

                cart.remove(productID);
                cart.put(productID, q + 1);
            } else {
                cart.put(productID, 1);
            }
        }

        return "cart";
    }

    @Override
    public String editCart(Map<String, Integer> newCart) {
        Set<String> keys = cart.keySet();
        Set<String> newKeys = newCart.keySet();

        for (Iterator<String> i = keys.iterator(); i.hasNext();) {
            String key = i.next();

            for (Iterator<String> j = newKeys.iterator(); j.hasNext();) {
                String newKey = j.next();

                if (key.equals(newKey)) {
                    Integer newValue = newCart.get(newKey);

                    cart.remove(key);
                    cart.put(key, newValue);
                }
            }
        }

        return "cart";
    }

    @Override
    public String removeCart() {
        cart.clear();

        return "cart";
    }

    @Override
    public String resetCart() {
        Set<String> keys = cart.keySet();

        for (Iterator<String> i = keys.iterator(); i.hasNext();) {
            String key = i.next();
            cart.remove(keys);

            cart.put(key, 1);
        }

        return "cart";
    }
}
